package com.pocket.demo.core.mq.rabbitMQ.demo;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.HashMap;
import java.util.Map;

/**
 * <p> 使用 延迟消息插件 实现延迟队列案例【demo-MQ-rabbitMQ-8】
 * <p> 实现步骤: <br>
 *      1. 下载插件：https://github.com/rabbitmq/rabbitmq-delayed-message-exchange，与MQ版本保持一致<br>
 *      2. 将插件 rabbitmq_delayed_message_exchange_*.ez 放置MQ的plugins目录下，/usr/local/Cellar/rabbitmq/3.13.2/plugins <br>
 *      3. 执行命令安装插件：rabbitmq-plugins enable rabbitmq_delayed_message_exchange
 *      4. 基于 Bean 的方式创建消费者，声明延迟队列，并绑定到延迟交换机
 *      5. 发送延迟消息，指定消息的延迟时间
 * <p> 参考地址:
 *      https://www.rabbitmq.com/blog/2015/04/16/scheduling-messages-with-rabbitmq <br>
 *      https://www.rabbitmq.com/blog/2015/04/16/scheduling-messages-with-rabbitmq <br>
 * @author cookie.
 **/
//@Configuration
public class PluginDeadExchangeConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(TTLDeadExchangeConfig.class);

    private static final String DELAY_EXCHANGE = "pocket.plugin.delay.direct";
    private static final String DELAY_QUEUE = "pocket.plugin.delay.queue";
    private static final String DELAY_ROUTING_KEY = "pocket.delay";

    @Resource
    private RabbitMessagingTemplate rabbitMessagingTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = DELAY_QUEUE, durable = "true"),
            exchange = @Exchange(name = DELAY_EXCHANGE, delayed = "true"), // 设置延迟属性为 true
            key = DELAY_ROUTING_KEY
    ))
    public void listenDelayMessage(String msg){
        LOGGER.debug("接收到delay.queue的延迟消息：{}", msg);
    }

    @Scheduled(fixedRate = 100000, initialDelay = 1000)
    public void sendMessage() {
        Map<String, Object> heads = new HashMap<>();
        heads.put("x-delay", 10000);
        rabbitMessagingTemplate.convertAndSend(DELAY_EXCHANGE, DELAY_ROUTING_KEY, "Scheduled delay message test", heads);
    }
}
